package br.com.sgmf.dao;

import java.util.Date;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import br.com.sgmf.enums.StatusOS;
import br.com.sgmf.model.OrdemServico;

@Repository
public class OrdemServicoDAO {

	@PersistenceContext
	private EntityManager manager;

	@Transactional
	public void save(OrdemServico ordemServico) {
		manager.persist(ordemServico);
	}

	@Transactional
	public void update(OrdemServico ordemServico) {
		manager.merge(ordemServico);
	}

	@Transactional
	public void delete(OrdemServico ordemServico) {
		ordemServico = manager.merge(ordemServico);
		manager.remove(ordemServico);
	}

	@Transactional(readOnly = true)
	public OrdemServico findById(Integer id) {
		return manager.find(OrdemServico.class, id);
	}

	@SuppressWarnings("unchecked")
	@Transactional(readOnly = true)
	public List<OrdemServico> findAll() {
		return manager.createNamedQuery("OrdemServico.findAll").getResultList();
	}

	// TODO: Usando hibernate criteria, deveria haver uma interface de DAO e uma
	// implementação se for usar hibernate
	@SuppressWarnings("unchecked")
	@Transactional(readOnly = true)
	public List<OrdemServico> findBetweenDate(Date inicio, Date fim,
			StatusOS statusOS) {
		Session session = getSession();
		Criteria criteria = session.createCriteria(OrdemServico.class);
		if (inicio != null) {
			criteria.add(Restrictions.ge("data", inicio));
		}
		if (fim != null) {
			criteria.add(Restrictions.le("data", fim));
		}
		if (statusOS != null) {
			criteria.add(Restrictions.eq("statusOS", statusOS));
		}
		return criteria.list();
	}

	private Session getSession() {
		return manager.unwrap(Session.class);
	}

}
